<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

/**
 * 权限检测，更新方法都在这。
 *
 * @ auth yunyun
 */

class Token_lib {
    
    var $CI	= NULL;
	var $_main_url = NULL;
	
	var $out_time = 600; //超时时间100s
    var $out_check_url = array(
        "login/index","login/quit","pic/up"
    );
    var $token_key = "Token";
    var $is_check = true;


    function __construct($config = array()) 
    {
    	$this->CI = & get_instance();
		log_message('debug', "Token_lib Class Initialized.");
    }

    /**
     * 添加令牌
     */
    public function adds($admin_id = 0){
        $this->CI->load->model("token/token_model");
        $token = NULL;
        if(!$this->CI->token_model->dels_admin($admin_id))
        {
            return NULL;
        }

        $num = 0;
        do{
            $token = $this->CI->token_model->adds($admin_id,$this->out_time);
            $num++;
            if($num > 5)
            {
                show_message("400",NULL,"添加令牌5次以上不成功，请联系管理员");
            }
        }while(!$token);
        return $token;
    }

    /**
     * 编辑令牌
     */
    public function check(){
        $headers = $this->CI->input->request_headers();
        $uri = uri_string();
        //print_r($uri);
        if(in_array($uri,$this->out_check_url)) return true; //如果是登录页面，不需要令牌

        if(!$this->is_check) {
            return false;
        }

        $this->CI->load->model("token/token_model");
        if(!isset($headers[$this->token_key]))
        {
            show_message("400",NULL,"headers令牌不存在");
        }
        $data_arr = $this->CI->token_model->info($headers[$this->token_key]);
        if($data_arr)
        {
            //比较一下超时时间。
            if($data_arr->extime < time()) show_message("400",NULL,"令牌超时");

            //没有超时，更新一下！！
            return $this->CI->token_model->edits($headers[$this->token_key],$this->out_time);

        }
        show_message("400",NULL,"令牌不存在");
    }


    //获取令牌
    public function get_data($type = NULL){
        $headers = $this->CI->input->request_headers();
        //print_r($headers);
        if(!isset($headers[$this->token_key])||$headers == NULL) {
            return NULL;
        }
        $this->CI->load->model("token/token_model");
        $data_arr = $this->CI->token_model->info($headers[$this->token_key]);
        if($data_arr)
        {
            if($type)
            {
                return @$data_arr->$type;
            }
            return $data_arr;
        }
        return NULL;
    }

    //写令牌数据
    public function set_data($token = NULL){
        if($token == NULL) {
            return NULL;
        }
    }




    /**
     * Initialize preferences
     *
     * @access	public
     * @param	array
     * @return	void
     */
    function initialize($config = array())
    {
		foreach ($config as $key => $val)
		{
			if (isset($this->$key))
			{
					$this->$key = $val;
			}
		}

    }
	
}
